package com.flight.view.components;

import com.flight.model.entity.Flight;
import com.flight.util.DateUtil;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 航班表格组件（显示航班列表并支持订票操作）
 */
public class FlightTable extends JTable {
    private DefaultTableModel tableModel;
    private List<Flight> flightList; // 存储航班数据
    private JButton bookingButton; // 订票按钮（用于渲染表格）

    public FlightTable() {
        // 初始化表格模型（设置列名，禁止单元格编辑）
        String[] columnNames = {"航班号", "出发地", "目的地", "日期", "时间", "余票", "操作"};
        tableModel = new DefaultTableModel(null, columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                // 仅"操作"列可编辑（第6列，从0开始计数）
                return column == 6;
            }
        };
        setModel(tableModel);

        // 初始化订票按钮
        bookingButton = new JButton("订票");
        bookingButton.setOpaque(true);

        // 设置"操作"列的渲染器和编辑器（显示按钮）
        getColumnModel().getColumn(6).setCellRenderer(new ButtonRenderer());
        getColumnModel().getColumn(6).setCellEditor(new ButtonEditor(new JCheckBox()));

        // 调整列宽
        setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    }

    /**
     * 更新表格数据
     * @param flights 航班列表
     */
    public void setFlightData(List<Flight> flights) {
        this.flightList = flights;
        tableModel.setRowCount(0); // 清空现有数据

        if (flights == null || flights.isEmpty()) {
            return;
        }

        // 填充表格数据
        for (Flight flight : flights) {
            Object[] rowData = {
                    flight.getFlightNo(),
                    flight.getDepartureCity(),
                    flight.getArrivalCity(),
                    DateUtil.formatDate(flight.getDepartureDate()), // 格式化日期
                    DateUtil.formatTime(flight.getDepartureTime()), // 格式化时间
                    flight.getRemainingSeats(),
                    "订票" // 操作列显示文本
            };
            tableModel.addRow(rowData);
        }
    }

    /**
     * 获取当前选中的航班
     * @return 选中的航班对象，未选中则返回null
     */
    public Flight getSelectedFlight() {
        int selectedRow = getSelectedRow();
        if (selectedRow >= 0 && flightList != null && selectedRow < flightList.size()) {
            return flightList.get(selectedRow);
        }
        return null;
    }

    /**
     * 绑定订票按钮点击事件
     * @param listener 事件监听器
     */
    public void setBookingActionListener(ActionListener listener) {
        bookingButton.addActionListener(listener);
    }

    /**
     * 自定义表格按钮渲染器（显示按钮）
     */
    private class ButtonRenderer extends DefaultTableCellRenderer implements TableCellRenderer {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            // 设置按钮文本（如"订票"）
            bookingButton.setText((value == null) ? "" : value.toString());
            // 选中行时高亮按钮背景
            if (isSelected) {
                bookingButton.setBackground(table.getSelectionBackground());
            } else {
                bookingButton.setBackground(table.getBackground());
            }
            return bookingButton;
        }
    }

    /**
     * 自定义表格按钮编辑器（处理按钮点击事件）
     */
    private class ButtonEditor extends AbstractCellEditor implements TableCellEditor {
        private JButton editorButton;
        private Object value;

        public ButtonEditor(JCheckBox checkBox) {
            editorButton = new JButton();
            editorButton.setOpaque(true);

            // 点击按钮时触发事件并停止编辑
            editorButton.addActionListener(e -> {
                fireEditingStopped(); // 通知表格停止编辑
                // 转发事件到外部监听器
                if (bookingButton.getActionListeners().length > 0) {
                    bookingButton.getActionListeners()[0].actionPerformed(e);
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            this.value = value;
            editorButton.setText((value == null) ? "" : value.toString());
            return editorButton;
        }

        @Override
        public Object getCellEditorValue() {
            return value;
        }
    }
}